// pages/mall/mall.js
let flag = 0
Page({

  /**
   * 页面的初始数据
   */
  data: {
    goods:[],
    category:[],
    currentType:0,
    //data_type:''//前台获取的商品类别
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // this.getGoodsCategory()
    flag = 0
    this.watchValue()
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.getGoodsCategory()
  },

  getGoodsDetail(params){
    //获取商品数据列表
    wx.cloud.database().collection('goods')
    .where({
      goods_category: params
    }).get()
    .then(res=>{
      //console.log(res)
      flag += 2
      this.setData({
        goods:res.data
      })
    })
  },
  //获取商品类别
  getGoodsCategory(){
    wx.cloud.database().collection('classify').get()
    .then(res=>{
      //console.log(res)
      this.setData({
        category:res.data
      })
      //在获得商品类别数据后才调用获取商品数据
      let temp = this.data.currentType
      //console.log(res.data[temp].goods_category)
      this.getGoodsDetail(res.data[temp].goods_category)
    })
  },
  //更新商品类别选中状态
  updateGoodsList(event){
    this.setData({
      currentType: event.currentTarget.dataset.index
    })
    // console.log(this.data.currentType)
    let temp1 = this.data.currentType
    let temp2 = this.data.category
    this.getGoodsDetail(temp2[temp1].goods_category)
  },
  // //跳转到商品详情页
  // toGoodsDetail(event){
  //   let id = event.currentTarget.dataset.id
  //   wx.navigateTo({
  //     url: '/pages/goodsDetail/goodsDetail?id=' + id,
  //   })
  // },
  onSearch() {
    this.toSearch()
  },
  onClick() {
    this.toSearch()
  },
  toSearch(){
    wx.navigateTo({
      url: '/pages/index/search/search',
    })
  },
  onShareAppMessage(res){
    let myObj = {
      title:'琪琪的手工饰品屋',
      path:"/pages/mall/mall",
    }
    return myObj;
  },
  watchValue() {
    wx.showLoading({
      title: '加载中',
    })
    // 定期检查flag的值
    var intervalId = setInterval(function () {
      if (flag === 2) {
        console.log('flag值更改为2')
        wx.hideLoading()
        // 在需要时关闭定时器
        clearInterval(intervalId)
      }
    })
  }
})